Trim a binary search tree¶
Time: O(N); Space: O(H); easy
Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L).
You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree.
Example 1:
Input: root = {TreeNode} [1,0,2], L = 1, R = 2
1
/ \
0 2
Output:
1
\
2
Example 2:
Input: root = {TreeNode} [3,0,4,None,2,None,None,None,None,1], L = 1, R = 3
3
/ \
0 4
\
2
/
1
Output:
3
/
2
/
1
[3]:
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
[4]:
class Solution1(object):
"""
Time: O(N)
Space: O(H)
"""
def trimBST(self, root, L, R):
"""
:type root: TreeNode
:type L: int
:type R: int
:rtype: do it in place
"""
if not root:
return None
if root.val < L:
return self.trimBST(root.right, L, R)
if root.val > R:
return self.trimBST(root.left, L, R)
root.left, root.right = self.trimBST(root.left, L, R), self.trimBST(root.right, L, R)
return root
[5]:
s = Solution1()
root = TreeNode(1)
root.left = TreeNode(0)
root.right = TreeNode(2)
L = 1
R = 2
s.trimBST(root, L, R)
assert root.val == 1
assert root.right.val == 2
root = TreeNode(3)
root.left = TreeNode(0)
root.right = TreeNode(4)
root.left.right = TreeNode(2)
root.left.right.left = TreeNode(1)
L = 1
R = 3
s.trimBST(root, L, R)
assert root.val == 3
assert root.left.val == 2
assert root.left.left.val == 1